import {
	productionPrdReportAudit, productionPrdReportClearAudit, productionPrdReportClearClose,
	productionPrdReportClearSubmitAudit, productionPrdReportClose,
	productionPrdReportCreate,
	productionPrdReportCreateAudit,
	productionPrdReportGet, productionPrdReportLtGetDate, productionPrdReportHistoryGet, productionPrdReportHistoryPage,
	productionPrdReportUpdate,
	productionPrdReportUpdateAudit
} from '../../../../../../api/production/xsReport';
import { formatDate, tipsBar } from '../../../../../../utils/jk/jk-tool';
import { openStateList, reportStateList } from '../../../../../../utils/jk/status-option-list';
import { spinProcessPage } from '../../../../../../api/technology/process';
import XEUtils from 'xe-utils';
import { workforcemanagementScheduleList } from '../../../../../../api/schedule/scheduling';
import { mathJsAdd, mathJsDiv, mathJsMul, mathJsSub } from '../../../../../../utils/jk/jk-cals';
let _this = null;
export default {
	components: {
	},
	props: {
		loading: {
			type: Boolean,
			default: false
		},
		pageType: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			apiItem: {
				'save': productionPrdReportCreate,
				'saveAudit': productionPrdReportCreateAudit,
				'update': productionPrdReportUpdate,
				'updateAudit': productionPrdReportUpdateAudit,
				'submit': productionPrdReportUpdate, // 后端暂时没有'保存并提交接口'，先用update代替
				'cancelSubmit': productionPrdReportClearSubmitAudit,
				'submitAudit': productionPrdReportUpdateAudit,
				'audit': productionPrdReportAudit,
				'cancelAudit': productionPrdReportClearAudit,
				'close': productionPrdReportClose,
				'cancelClose': productionPrdReportClearClose
			},
			reportStateList: reportStateList,
			tableLoading: false,
			openStateList: openStateList,
			dataId: null,
			showLoading: false,
			updateAuditLoading: false,
			saveAuditLoading: false,
			saveBtnLoading: false,
			workshopList: [],
			processList: [],
			saveDialogState: false,
			scheduleShiftList: [],
			historyData: [],
			ruleForm: {
				'code': '编号自动生成',
				'type': 2,
				'generateType': 1,
				'belongDate': '',
				'historyCount': 0,
				'prdReportMachineList': [],
				'processCode': '',
				'processId': null,
				'processName': '',
				'scheduleShiftId': null,
				'shiftElectricEnergy': null,
				'shiftId': null,
				'shiftName': '',
				'shiftOutput': null,
				'shiftQty': null,
				'wasteRate': null,
				'workshopId': null,
				'workshopName': '',
				'remark': ''
			},
			rules: {
				processId: [{ required: true, trigger: 'change' }],
				belongDate: [{ required: true, trigger: 'change' }],
				scheduleShiftId: [{ required: true, trigger: 'change' }],
				workshopId: [{ required: true, trigger: 'change' }]
			},
			colorList: ['#ecf5ff', '#fef0f0', '#e8ddf6', '#f5fff0', '#f4f4f5', '#fdf6ec'],
			machineStyleConfig: {}
		};
	},
	methods: {
		setMachineStyle(arr = []) {
			let machineCodeList = arr.map(x => x.machineCode);
			machineCodeList = Array.from(new Set(machineCodeList));
			let idx = 0;
			machineCodeList.forEach((item, index) => {
				idx = index;
				if (index > this.colorList.length) {
					idx = 0;
					this.machineStyleConfig[item] = this.colorList[idx];
				} else {
					this.machineStyleConfig[item] = this.colorList[idx];
				}
			});
		},
		rowClassName({ row }) {
			return {
				backgroundColor: this.machineStyleConfig[row.machineCode]
			};
		},
		mergeColMethod({ row, _rowIndex, column, visibleData }) {
			const fields = ['machineCode'];
			const cellValue = row[column.property];
			if (cellValue && fields.includes(column.property)) {
				const prevRow = visibleData[_rowIndex - 1];
				let nextRow = visibleData[_rowIndex + 1];
				if (prevRow && prevRow[column.property] === cellValue) {
					return { rowspan: 0, colspan: 0 };
				} else {
					let countRowspan = 1;
					while (nextRow && nextRow[column.property] === cellValue) {
						nextRow = visibleData[++countRowspan + _rowIndex];
					}
					if (countRowspan > 1) {
						return { rowspan: countRowspan, colspan: 1 };
					}
				}
			}
		},
		// 输入,开始能耗表数
		onStartElectricEnergy(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'startElectricEnergy', e);
			this.calMachineItemVal(scope);
		},
		// 输入,结束能耗表数
		onEndElectricEnergy(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'endElectricEnergy', e);
			this.calMachineItemVal(scope);
		},
		// 输入,开始产量表数
		onStartOutput(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'startOutput', e);
			this.calMachineItemVal(scope);
		},
		// 输入,当班能耗表数
		onShiftElectricEnergy(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftElectricEnergy', e);
			this.calMachineItemVal(scope);
		},
		// 输入,结束产量表数
		onEndOutput(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'endOutput', e);
			this.calMachineItemVal(scope);
		},
		onOutputRatio(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'outputRatio', e);
			this.calMachineItemVal(scope);
		},
		calMachineItemVal(scope, isFromDifferenceValue = false) {
			 /**
			 * 第一, 当班产量表量KG = 结束表量 - 开始表量
			 * */
			 // let valKg1 = mathJsMul(scope.row.endOutput, scope.row.startOutput);
			let valKg1 = scope.row.shiftQty;
			valKg1 = mathJsMul(valKg1, scope.row.outputRatio);
			valKg1 = parseFloat(valKg1.toFixed(2));
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftQty', valKg1);

			/**
			 *  第二,计算当班能耗表数
			 *  */
			// 当班能耗表数 = 结束能耗表数 - 开始能耗表数
			/* let energyVal = mathJsSub(scope.row.endElectricEnergy, scope.row.startElectricEnergy);
			energyVal = parseFloat(energyVal.toFixed(2));
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftElectricEnergy', energyVal);*/
		},
		footerMethod({ columns, data }) {
			const keys = ['shiftQty', 'shiftOutput', 'shiftElectricEnergy', 'differenceValue'];
			return [
				columns.map((column, columnIndex) => {
					if (columnIndex === 0) {
						return '合计';
					}
					if (keys.includes(column.field)) {
						return XEUtils.sum(data, column.field);
					}
					return null;
				})
			];
		},
		onWorkshopChange() {
			this.$set(this.ruleForm, 'processId', null);
			this.$set(this.ruleForm, 'prdReportMachineList', []);
			this.$set(this.ruleForm, 'scheduleShiftId', null);
			this.$set(this.ruleForm, 'shiftId', null);
			this.$set(this.ruleForm, 'shiftName', null);
			this.scheduleShiftList = [];
			this.getProcessListRequest();
			this.getDateScheduleShiftOptionRequest();
		},
		onProcessChange() {
			this.$set(this.ruleForm, 'prdReportMachineList', []);
		},
		transformRouterName() {
			let name = this.$route.query.processCode;
			name = name.toLowerCase();
			return `${name.charAt(0).toUpperCase()}${name.substring(1, name.length)}`;
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: `${this.transformRouterName()}Report`
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: `edit${this.transformRouterName()}Report`,
				query: {
					id: id,
					processCode: this.$route.query.processCode
				}
			});
		},
		setDependentDataOfForm() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.prdReportMachineList = this.ruleForm.prdReportMachineList.map(x => x);

			params.workshopCode = this.workshopList.find(x => x.id === params.workshopId).code;
			params.workshopName = this.workshopList.find(x => x.id === params.workshopId).name;

			params.processCode = this.processList.find(x => x.id === params.processId).code;
			params.processName = this.processList.find(x => x.id === params.processId).name;

			params.shiftId = this.scheduleShiftList.find(x => x.id === params.scheduleShiftId).shiftId;
			params.shiftName = this.scheduleShiftList.find(x => x.id === params.scheduleShiftId).shiftName;

			return params;
		},
		onConfirmBtn() {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.createAndUpdateRequest();
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		},
		createAndUpdateRequest() {
			this.saveBtnLoading = true;
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				productionPrdReportCreate(this.setDependentDataOfForm()).then(res => {
					this.saveBtnLoading = false;
					if (res.data.status === 200) {
						this.$tipsBar(this, 'save');
						this.onJump(res.data.res);
					}
				});
				return;
			}
			// 编辑
			productionPrdReportUpdate(this.setDependentDataOfForm()).then(res => {
				this.saveBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.getDependentData();
				}
			});
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		getDetailRequest() {
			let api = null;
			if (this.$route.query.formPage && this.$route.query.formPage === 'history') {
				api = productionPrdReportHistoryGet;
			} else {
				api = productionPrdReportGet;
			}
			return api({ id: this.$route.query.id }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					this.setMachineStyle(resData.prdReportMachineList || []);
					this.ruleForm = resData || {};

					this.calTotal();
				}
			});
		},
		onSeeHistory(row) {
			this.$toOtherRouter({
				name: 'detailXsReport',
				query: {
					id: row.id,
					formPage: 'history'
				}
			});
			this.getDependentData();
		},
		onScheduleShiftChange(e) {
			let item = {};
			if (e) {
				item = this.scheduleShiftList.find(x => x.id === e);
			} else {
				item = {
					id: null,
					shiftId: null,
					shiftName: null,
					scheduleId: null
				};
			}
			this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
			this.$set(this.ruleForm, 'scheduleShiftId', item.id);
			this.$set(this.ruleForm, 'shiftId', item.shiftId);
			this.$set(this.ruleForm, 'shiftName', item.shiftName);
			this.getOpenMachineListRequest();
		},
		getOpenMachineListRequest() {
			if (this.ruleForm.workshopId && this.ruleForm.processId && this.ruleForm.belongDate && this.ruleForm.scheduleShiftId) {
				this.tableLoading = true;
				productionPrdReportLtGetDate({
					workshopId: this.ruleForm.workshopId,
					processId: this.ruleForm.processId,
					shiftId: this.ruleForm.shiftId,
					scheduleShiftId: this.ruleForm.scheduleShiftId,
					belongDate: this.ruleForm.belongDate
				}).then(res => {
					this.tableLoading = false;
					if (res.data.status === 200) {
						this.setMachineStyle(res.data.res || []);
						this.$set(this.ruleForm, 'prdReportMachineList', res.data.res);
						this.calTotal();
					}
				});
			}
		},
		calTotal() {
			let valM = 0;
			let valKg = 0;
			let valEn = 0;
			this.ruleForm && this.ruleForm.prdReportMachineList ? this.ruleForm.prdReportMachineList.forEach(x => {
				valM = mathJsAdd(x.shiftOutput || 0, valM);
				valKg = mathJsAdd(x.shiftQty || 0, valKg);
				valEn = mathJsAdd(x.shiftElectricEnergy || 0, valEn);
			}) : [];
			this.$set(this.ruleForm, 'shiftOutput', valM);
			this.$set(this.ruleForm, 'shiftQty', valKg);
			this.$set(this.ruleForm, 'shiftElectricEnergy', valEn);
		},
		getDateScheduleShiftOptionRequest() {
			if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
				return workforcemanagementScheduleList({
					belongDate: [this.ruleForm.belongDate, this.ruleForm.belongDate],
					workshopId: this.ruleForm.workshopId
				}).then(res => {
					if (res.data.status === 200) {
						const resData = res.data.res;
						if (resData && resData.length) {
							this.scheduleShiftList = resData[0].scheduleShiftList;
						} else {
							tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
						}
					}
				});
			}
		},
		getProcessListRequest() {
			return spinProcessPage({ code: this.$route.query.processCode, workshopId: this.ruleForm.workshopId }).then(res => {
				if (res.data.status === 200) {
					this.processList = res.data.res;
					if (res.data.res && res.data.res.length) {
						const item = res.data.res[0];
						this.$set(this.ruleForm, 'processId', item.id);
						this.$set(this.ruleForm, 'processCode', item.code);
						this.$set(this.ruleForm, 'processName', item.name);
					}
				}
			});
		},
		onDateChange() {
			this.$set(this.ruleForm, 'scheduleShiftId', null);
			this.$set(this.ruleForm, 'shiftName', null);
			this.$set(this.ruleForm, 'shiftId', null);
			this.$set(this.ruleForm, 'prdReportMachineList', []);
			this.scheduleShiftList = [];
			this.getDateScheduleShiftOptionRequest();
		},
		getHistoryDataRequest() {
			return productionPrdReportHistoryPage({
				selectMaster: false,
				prdReportId: this.ruleForm.prdReportId ? this.ruleForm.prdReportId : this.ruleForm.id
			}).then(res => {
				if (res.data.status === 200) {
					this.historyData = res.data.res;
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			if (this.pageType !== 'detail') {
				this.workshopList = this.$store.state.user.userWorkshop.workshopList;
				if (!this.dataId) {
					this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
					this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
					this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
					this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
				}
			}
			await this.getProcessListRequest();
			if (this.dataId) await this.getDetailRequest();
			await this.getDateScheduleShiftOptionRequest();
			await this.getHistoryDataRequest();
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate([]);
			});
			this.showLoading = false;
		},
		clearCacheData() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	},
	watch: {
		ruleForm: {
			handler() {
				this.$refs.jkTable.$refs.xTable.updateFooter();
				this.calTotal();
			},
			deep: true
		}
	},
	mounted() {
		_this = this;
	}
};
